<template>
  <div class="materials-page">
    <div class="content">
      <!-- 分类树 -->
      <div class="category-tree">
        <div class="tree-header">
          <el-input
            v-model="categoryKeyword"
            placeholder="搜索分类名称"
            clearable
            class="tree-search"
            @keyup.enter.native="() => {}"
          />
          <el-tooltip content="新增分类" placement="top">
            <el-button circle @click="onAddCategory()">
              <el-icon><Plus /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
        <el-tree
          class="tree"
          :data="filteredCategoryTree"
          :props="treeProps"
          node-key="id"
          highlight-current
          default-expand-all
          @node-click="onCategoryClick"
        >
          <template #default="{ data }">
            <div class="tree-node">
              <span class="label">
                {{ data.name }}
                <el-tooltip v-if="data.remark" :content="data.remark" placement="top" effect="dark">
                  <el-icon class="remark-icon"><QuestionFilled /></el-icon>
                </el-tooltip>
              </span>
              <el-dropdown trigger="click">
                <span class="more-trigger" @click.stop.prevent>
                  <el-icon><More /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="!data.parentId"
                      @click.stop="() => onAddSubCategoryFromNode(data)"
                    >
                      新增子类
                    </el-dropdown-item>
                    <el-dropdown-item @click.stop="() => onEditCategoryFromNode(data)">
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item @click.stop="() => onDeleteCategoryFromNode(data)">
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-tree>
      </div>

      <!-- 表格区域 -->
      <div class="table-area">
        <!-- 右侧顶部 搜索与工具栏 -->
        <div class="table-toolbar">
          <div>
            <el-button type="primary" @click="onCreateMaterial">新建物料</el-button>
            <el-button :disabled="!hasSelection" @click="onBatchEnable">批量启用</el-button>
            <el-button :disabled="!hasSelection" @click="onBatchDisable">批量禁用</el-button>
            <el-button type="danger" :disabled="!hasSelection" @click="onBatchDelete">
              批量删除
            </el-button>
            <el-button :disabled="!hasSelection" @click="() => onMoveTo()">批量移动至</el-button>
          </div>
          <el-input
            v-model="query.keyword"
            placeholder="物料名称/描述"
            clearable
            @keyup.enter.native="handleSearch"
            style="width: 260px"
          />
        </div>

        <el-table
          :data="tableData"
          v-loading="loading"
          @selection-change="onSelectionChange"
          border
          height="100%"
          style="width: 100%"
        >
          <el-table-column type="selection" width="48" />
          <el-table-column
            prop="materialName"
            label="物料名称"
            min-width="160"
            show-overflow-tooltip
          />
          <el-table-column prop="remark" label="描述" min-width="220" show-overflow-tooltip />
          <el-table-column prop="version" label="当前版本" min-width="120" show-overflow-tooltip />
          <el-table-column label="状态" width="200">
            <template #header>
              <div class="table-header-filter">
                <span>状态</span>
                <el-popover
                  placement="bottom"
                  :width="200"
                  trigger="click"
                  v-model:visible="statusFilterVisible"
                >
                  <template #reference>
                    <el-icon class="filter-icon" @click.stop>
                      <Search />
                    </el-icon>
                  </template>
                  <div class="filter-content">
                    <el-select
                      v-model="query.status"
                      placeholder="选择状态"
                      clearable
                      style="width: 100%"
                      @change="handleSearch"
                    >
                      <el-option label="全部" value="" />
                      <el-option label="启用" :value="1" />
                      <el-option label="禁用" :value="2" />
                    </el-select>
                  </div>
                </el-popover>
              </div>
            </template>
            <template #default="{ row }">
              <el-switch
                :model-value="row.status === '1'"
                :active-text="row.status === '1' ? '启用' : '禁用'"
                inline-prompt
                @change="(val) => onToggleStatus(row, val)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createBy" label="创建人" min-width="120" show-overflow-tooltip />
          <el-table-column prop="updateTime" min-width="250">
            <template #header>
              <div class="table-header-filter">
                <span>最近修改时间</span>
                <el-popover
                  placement="bottom"
                  :width="360"
                  trigger="click"
                  v-model:visible="timeFilterVisible"
                >
                  <template #reference>
                    <el-icon class="filter-icon" @click.stop>
                      <Search />
                    </el-icon>
                  </template>
                  <div class="filter-content">
                    <el-date-picker
                      v-model="query.updatedRange"
                      type="datetimerange"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      range-separator="至"
                      :default-time="['00:00:00', '23:59:59']"
                      style="width: 100%"
                      clearable
                      @change="handleSearch"
                    />
                  </div>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260" fixed="right">
            <template #default="{ row }">
              <div class="handle_btn_list">
                <el-link type="primary" :underline="false" @click="onView(row)">查看</el-link>
                <el-link type="primary" :underline="false" @click="onEdit(row)">编辑</el-link>
                <el-link type="primary" :underline="false" @click="onCopy(row)">复制</el-link>
                <el-link type="primary" :underline="false" @click="onDownloadTemplate(row)">
                  下载模板
                </el-link>
                <el-dropdown>
                  <el-link type="primary" :underline="false">
                    移动至
                    <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-link>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="() => onMoveTo(row)">选择分类...</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pager">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            v-model:current-page="query.pageNum"
            v-model:page-size="query.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="handleSearch"
            @current-change="handleSearch"
          />
        </div>
      </div>
    </div>

    <!-- 物料表单弹窗 -->
    <el-dialog v-model="materialDialogVisible" title="新建物料" width="640px">
      <el-form
        :model="materialForm"
        :rules="materialRules"
        ref="materialFormRef"
        label-width="96px"
      >
        <el-form-item label="物料名称" prop="name">
          <el-input v-model="materialForm.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="所属分类" prop="classification">
          <el-tree-select
            v-model="materialForm.classification"
            :data="categoryTree"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            check-strictly
            placeholder="请选择分类"
            style="width: 100%"
            node-key="id"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="materialForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入描述，128字符以内"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="materialDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitMaterial">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 分类弹窗 -->
    <el-dialog v-model="categoryDialog.visible" :title="categoryDialog.title" width="520px">
      <el-form
        :model="categoryForm"
        :rules="categoryRules"
        ref="categoryFormRef"
        label-width="84px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类描述" prop="remark">
          <el-input
            v-model="categoryForm.remark"
            placeholder="请输入分类描述"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="上级分类">
          <el-tree-select
            v-model="categoryForm.parentId"
            :data="categoryTree"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            check-strictly
            clearable
            placeholder="（无上级为根分类）"
            style="width: 100%"
            node-key="id"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitCategory">保 存</el-button>
      </template>
    </el-dialog>

    <!-- 移动至弹窗 -->
    <el-dialog v-model="moveDialog.visible" title="移动至" width="560px">
      <el-form label-width="84px" class="move-form">
        <el-form-item label="物料名称">
          <div class="selected-preview">已选择{{ moveDialog.targetIds.length }}个物料</div>
        </el-form-item>
        <el-form-item label="所属分类">
          <el-tree-select
            v-model="moveDialog.targetCategoryId"
            :data="categoryTree"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            check-strictly
            placeholder="请选择目标分类"
            style="width: 100%"
            node-key="id"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="moveDialog.visible = false">取 消</el-button>
        <el-button type="primary" :disabled="!moveDialog.targetCategoryId" @click="onConfirmMove">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  addClassification,
  createMaterial,
  deleteClassification,
  downloadTemplate,
  enableDisable,
  getClassificationTree,
  getMaterialPage,
  move,
  removeMaterial,
  updateClassification
} from '@/api/system/materials'
import { ArrowDown, More, Plus, QuestionFilled, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

// 查询参数
const query = reactive({
  keyword: '',
  status: undefined,
  updatedRange: [],
  categoryId: undefined,
  pageNum: 1,
  pageSize: 10
})

const router = useRouter()
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const multipleSelection = ref([])
const hasSelection = computed(() => multipleSelection.value.length > 0)

// 表头过滤器状态
const statusFilterVisible = ref(false)
const timeFilterVisible = ref(false)

// 分类树
const categoryTree = ref([])
const currentCategory = ref(null)
const treeProps = { label: 'name', children: 'children' }
const categoryKeyword = ref('')
const filteredCategoryTree = computed(() => {
  const kw = categoryKeyword.value.trim().toLowerCase()
  if (!kw) return categoryTree.value
  function matchNode(node) {
    const selfMatch = (node.name || '').toLowerCase().includes(kw)
    const children = node.children || []
    const filteredChildren = []
    for (const c of children) {
      const r = matchNode(c)
      if (r) filteredChildren.push(r)
    }
    if (selfMatch || filteredChildren.length) {
      return { ...node, children: filteredChildren }
    }
    return null
  }
  const result = []
  for (const n of categoryTree.value) {
    const r = matchNode(n)
    if (r) result.push(r)
  }
  return result
})

// 静态物料全集
const allMaterials = ref([])

// 物料表单
const materialDialogVisible = ref(false)
const materialFormRef = ref()
const materialForm = reactive({
  materialName: '',
  remark: '',
  classification: undefined
})
const materialRules = {
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  classification: [{ required: true, message: '请选择分类', trigger: 'change' }]
}

// 分类表单
const categoryDialog = reactive({ visible: false, title: '新增分类', mode: 'create' })
const categoryFormRef = ref()
const categoryForm = reactive({ id: undefined, name: '', parentId: undefined, remark: '' })
const categoryRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
}

// 移动至
const moveDialog = reactive({ visible: false, targetIds: [], targetCategoryId: undefined })

function normalizeTimerange(range) {
  if (!range || (Array.isArray(range) && range.length === 0))
    return { beginTime: undefined, endTime: undefined }
  const [beginTime, endTime] = range
  return { beginTime, endTime }
}

async function fetchList() {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageNum: query.pageNum,
      pageSize: query.pageSize,
      materialName: query.keyword || undefined,
      status: query.status,
      classification: query.categoryId,
      ...normalizeTimerange(query.updatedRange)
    }
    const res = await getMaterialPage(params)
    tableData.value = res.data.list || []
    total.value = res.data.total || 0
  } catch (err) {
  } finally {
    loading.value = false
  }
}

async function fetchCategories() {
  getClassificationTree().then((res) => {
    categoryTree.value = res.data
  })
}

function handleSearch(page) {
  query.pageNum = typeof page === 'number' ? page : 1
  fetchList()
}

function handleReset() {
  query.keyword = ''
  query.status = undefined
  query.updatedRange = []
  query.categoryId = undefined // 重置分类选择
  query.pageNum = 1
  query.pageSize = 10
  currentCategory.value = null // 清空当前选中的分类
  fetchList()
}

function onSelectionChange(rows) {
  multipleSelection.value = rows
}

function onCategoryClick(node) {
  currentCategory.value = node
  query.categoryId = node?.id
  query.pageNum = 1 // 重置到第一页
  handleSearch()
}

function onCreateMaterial() {
  materialForm.materialName = ''
  materialForm.remark = ''
  materialForm.classification = ''
  materialDialogVisible.value = true
}

function onEdit(row) {
  router.push({ path: `/system/materials-detail/edit/${row.id}` })
}

function onCopy(row) {
  ElMessage.info(`复制物料${row.materialName}`)
}

function onView(row) {
  router.push({ path: `/system/materials-detail/view/${row.id}` })
}

async function onSubmitMaterial() {
  await materialFormRef.value?.validate()
  const payload = { ...materialForm }
  // 调用创建接口
  const res = await createMaterial(payload)
  const targetId = res.data
  ElMessage.success('创建成功')
  materialDialogVisible.value = false
  fetchList()
  // 跳转物料编辑
  if (targetId) {
    router.push({ path: `/system/materials-detail/edit/${targetId}` })
  }
}

async function onBatchDelete() {
  const ids = multipleSelection.value.map((i) => i.id)
  if (!ids.length) return
  await ElMessageBox.confirm(`确定删除选中的 ${ids.length} 条记录吗？`, '提示', {
    type: 'warning'
  })
  await removeMaterial({ ids })
  ElMessage.success('删除成功')
  fetchList()
}

async function onBatchEnable() {
  const ids = multipleSelection.value.map((i) => i.id)
  if (!ids.length) return
  await ElMessageBox.confirm(`确定启用选中的 ${ids.length} 条记录吗？`, '提示', {
    type: 'warning'
  })
  // 调用启用接口
  await enableDisable({ ids, status: '1' })
  ElMessage.success('已启用')
  fetchList()
}

async function onBatchDisable() {
  const ids = multipleSelection.value.map((i) => i.id)
  if (!ids.length) return
  await ElMessageBox.confirm(`确定禁用选中的 ${ids.length} 条记录吗？`, '提示', {
    type: 'warning'
  })
  // 调用禁用接口
  await enableDisable({ ids, status: '2' })
  ElMessage.success('已禁用')
  fetchList()
}

async function onToggleStatus(row, val) {
  const targetText = val ? '启用' : '禁用'
  try {
    await ElMessageBox.confirm(`确定${targetText}该物料「${row.materialName}」吗？`, '提示', {
      type: 'warning'
    })
  } catch (e) {
    // 还原显示
    await nextTick()
    row.status = row.status === '1' ? '1' : '2'
    return
  }
  enableDisable({ ids: [row.id], status: val ? '1' : '2' })
    .then((res) => {
      ElMessage.success(`${targetText}成功`)
    })
    .catch(() => {
      row.status = row.status === '1' ? '1' : '2'
    })
}

function onMoveTo(row) {
  moveDialog.visible = true
  moveDialog.targetCategoryId = undefined
  moveDialog.targetIds = row ? [row.id] : multipleSelection.value.map((i) => i.id)
}

async function onConfirmMove() {
  if (!moveDialog.targetCategoryId || moveDialog.targetIds.length === 0) return
  // 调用移动接口
  await move({
    ids: moveDialog.targetIds,
    classificationId: moveDialog.targetCategoryId
  })
  ElMessage.success('移动成功')
  moveDialog.visible = false
  fetchList()
}

async function onDownloadTemplate(row) {
  // 调用下载模板接口
  const res = await downloadTemplate({ id: row.id })
  // 创建下载链接
  const blob = new Blob([res], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = '物料模板.xlsx'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  ElMessage.success('模板下载成功')
}

// 分类 CRUD
function onAddCategory(parent) {
  categoryDialog.title = '新增分类'
  categoryDialog.mode = 'create'
  categoryForm.id = undefined
  categoryForm.name = ''
  categoryForm.parentId = parent?.id
  categoryForm.remark = ''
  categoryDialog.visible = true
}

// 节点菜单触发
function onEditCategoryFromNode(node) {
  currentCategory.value = node
  categoryDialog.title = '编辑分类'
  categoryDialog.mode = 'edit'
  categoryForm.id = node.id
  categoryForm.name = node.name
  categoryForm.parentId = node.parentId
  categoryForm.remark = node.remark || ''
  categoryDialog.visible = true
}

function onAddSubCategoryFromNode(node) {
  currentCategory.value = node
  // 限制最多二级：若当前为二级（存在 parentId 且 parentId != 0），则不允许再加子类
  if (node.parentId && node.parentId !== 0) {
    ElMessage.warning('最多支持二级分类，无法继续新增子类')
    return
  }
  onAddCategory(node)
}

async function onDeleteCategoryFromNode(node) {
  await ElMessageBox.confirm(`确定删除分类「${node.name}」吗？`, '提示', { type: 'warning' })
  deleteClassification({ id: node.id }).then((res) => {
    if (currentCategory.value && currentCategory.value.id === node.id) {
      currentCategory.value = null
      query.categoryId = undefined
    }
    ElMessage.success('删除成功')
    fetchCategories()
  })
}

async function onSubmitCategory() {
  await categoryFormRef.value?.validate()
  try {
    // 限制：最多二级
    if (categoryForm.parentId) {
      const parent = findCategoryById(categoryTree.value, categoryForm.parentId)
      if (parent && parent.parentId && parent.parentId !== 0) {
        ElMessage.warning('最多支持二级分类，请选择上级为根分类或一级分类')
        return
      }
    }
    if (categoryDialog.mode === 'edit') {
      updateClassification({
        id: categoryForm.id,
        name: categoryForm.name,
        parentId: categoryForm.parentId || 0,
        remark: categoryForm.remark || ''
      }).then((res) => {
        ElMessage.success('修改成功')
        categoryDialog.visible = false
        fetchCategories()
      })
    } else {
      const newId = generateCategoryId(categoryTree.value)
      const newNode = {
        id: newId,
        name: categoryForm.name,
        parentId: categoryForm.parentId || '',
        remark: categoryForm.remark || ''
      }
      addClassification(newNode).then((res) => {
        ElMessage.success('新增成功')
        categoryDialog.visible = false
        fetchCategories()
      })
    }
  } catch (e) {}
}

onMounted(async () => {
  await fetchCategories()
  await fetchList()
})

// 分类辅助
function findCategoryById(tree, id) {
  for (const n of tree) {
    if (n.id === id) return n
    if (n.children && n.children.length) {
      const r = findCategoryById(n.children, id)
      if (r) return r
    }
  }
  return null
}

function generateCategoryId(tree) {
  const ids = []
  ;(function walk(nodes) {
    for (const n of nodes) {
      ids.push(n.id)
      if (n.children && n.children.length) walk(n.children)
    }
  })(tree)
  return (Math.max(0, ...ids) || 0) + 1
}
</script>

<style lang="scss" scoped>
.materials-page {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100%;

  .content {
    display: grid;
    grid-template-columns: 250px 1fr;
    gap: 12px;
    flex: 1;
    min-height: 0;

    .category-tree {
      background: #fff;
      border-right: 1px solid #ebeef5;
      padding: 12px;
      min-height: 0;
      display: flex;
      flex-direction: column;

      .tree-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 8px;
        font-weight: 500;
      }

      .tree {
        flex: 1;
        overflow: auto;
        :deep(.el-tree-node__content) {
          padding-right: 8px;
        }
      }
    }

    .table-area {
      background: #fff;
      border-radius: 6px;
      padding: 12px;
      min-height: 0;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .table-toolbar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12px;
      }

      .pager {
        padding-top: 8px;
        display: flex;
        justify-content: flex-end;
      }
    }
  }

  :deep(.el-table) {
    --el-table-border-color: #ebeef5;
  }

  :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}

.move-tree {
  max-height: 420px;
  overflow: auto;
}

.tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  .label {
    display: inline-flex;
    align-items: center;
    gap: 4px;
  }
  .remark-icon {
    color: #909399;
    font-size: 14px;
  }
  .more-trigger {
    display: inline-flex;
    align-items: center;
    color: #909399;
    cursor: pointer;
    transform: rotate(90deg);
    &:hover {
      color: #606266;
    }
  }
}

.move-form .selected-preview {
  color: #606266;
}
.handle_btn_list {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-header-filter {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;

  .filter-icon {
    cursor: pointer;
    color: #909399;
    font-size: 14px;
    margin-left: 8px;

    &:hover {
      color: #409eff;
    }
  }
}

.filter-content {
  padding: 8px 0;
}
</style>
